﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using TestGenerator.Input;
using TestGenerator.Generator;

namespace TestGenerator.Output
{
    public class OutputCreator
    {
        private int CurrentTestNum;

        public OutputCreator()
        {
            CurrentTestNum = 0;
        }

        public void BuildTests() 
        {
            if (CurrentTestNum == 0)
            {
                try
                {
                    File.Create(TestResource.Initialize.AnswersFileName).Close();
                }
                catch (Exception e)
                {
                    throw new IOException("Problem with creating file " + TestResource.Initialize.AnswersFileName + " !", e);
                }
            }
            WriteAnswersHeader(TestResource.Initialize.AnswersFileName);
            for (int i = 1; i <= TestResource.Initialize.MaxQuestions; i++) 
            {
                BuildNextTest();
            }
            WriteAnswersFooter();
        }

        private void WriteAnswersHeader(string fileName)
        {
            string answersHeader = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1251\"><title>Test answers</title></head><body lang=BG><div class=Section1><table class=MsoTableGrid border=1 cellspacing=0 cellpadding=0 style='margin-left:.25pt;border-collapse:collapse;border:none'> <tr style='height:3.15pt'> <td width=34 valign=top style='width:25.35pt;border:solid windowtext 1.0pt; padding:2.85pt 0cm 2.85pt 0cm;height:3.15pt'> <p class=MsoNormal align=center style='text-align:center;text-indent:0cm'><span style='font-size:10.0pt;font-family:Tahoma'>Вар.</span></p> </td>\n\n";
            string answersFooter = "</tr>";
            using (StreamWriter writer = new StreamWriter(fileName, true, Encoding.GetEncoding("windows-1251")))
            {
                writer.Write(answersHeader);
                for (int i = 1; i <= TestResource.Initialize.MaxQuestions; i++) 
                {
                    string answerHeader = "<td width=22 style='width:16.6pt;border:solid windowtext 1.0pt;border-left:none;padding:2.85pt 0cm 2.85pt 0cm;height:3.15pt'><p class=MsoNormal align=center style='text-align:center;text-indent:0cm'><span lang=EN-US style='font-size:10.0pt;font-family:Tahoma'>";
                    string answerFooter = "</span></p></td>\n\n";
                    writer.Write(answerHeader + i + answerFooter);
                    writer.Flush();
                }
                writer.Write(answersFooter);
                writer.Flush();
            }
        }

        private void WriteAnswersFooter() 
        {
            string footer = "</table><p class=Question>&nbsp;</p></div></body></html>";
            using (StreamWriter writer = new StreamWriter(TestResource.Initialize.AnswersFileName, true, Encoding.GetEncoding("windows-1251")))
            {
                writer.Write(footer);
                writer.Flush();
            }
        }

        private void BuildNextTest()
        {
            string outputFileName = TestResource.Initialize.OutputFileNamePrefix + CurrentTestNum.ToString().PadLeft(3, '0') + ".html";
            try
            {
                File.Create(outputFileName).Close();
            }
            catch (Exception e)
            {
                throw new IOException("Problem with creating file " + outputFileName + " !", e);
            }
            WriteHeader(outputFileName);
            WriteQuestionsAndAnswersTable(outputFileName);
            WriteFooter(outputFileName);
            CurrentTestNum++;
        }

        private void WriteHeader(string fileName)
        {
            using (StreamWriter writer = new StreamWriter(fileName, true, Encoding.GetEncoding("windows-1251")))
            {
                string headerString = TestBuilder.Resource.Heather;
                headerString = headerString.Replace("# # #</p>", CurrentTestNum.ToString().PadLeft(3, '0'));
                writer.Write(headerString);
            }
        }

        private void WriteQuestionsAndAnswersTable(string fileName)
        {
            using (StreamWriter questionWriter = new StreamWriter(fileName, true, Encoding.GetEncoding("windows-1251")))
            {
                List<string> correctAnswers = new List<string>();
                TestBuilder generator = new TestBuilder();
                List<GeneratedQuestion> questions = TestBuilder.BuildCompleteTest();
                int numQuestion = 1;
                foreach (GeneratedQuestion question in questions)
                {
                    string questionHeader =
                        "<p class=Question>" + numQuestion + ". " + question.Name + "</p>\n\n";
                    questionWriter.Write(questionHeader + "</p>");
                    string questionAnswers = "";
                    int answerNum = 1;
                    foreach (string answerText in question.Answers)
                    {
                        questionAnswers += "<p class=Answer>";
                        questionAnswers += (char)((int)('a' + answerNum - 1)) + ") ";
                        questionAnswers += answerText;
                        questionAnswers += "</p>\n\n";
                        answerNum++;
                    }
                    questionWriter.Write(questionAnswers);
                    correctAnswers.Add((char)((int)('a' + question.CorrectAnswerIndex)) + "");
                    numQuestion++;
                }

                using (StreamWriter correctAnswersWriter = new StreamWriter(TestResource.Initialize.AnswersFileName, true, Encoding.GetEncoding("windows-1251"))) 
                {
                    string answerMainHeader = "<td width=34 valign=top style='width:25.35pt;border:solid windowtext 1.0pt; padding:2.85pt 0cm 2.85pt 0cm;height:3.15pt'> <p class=MsoNormal align=center style='text-align:center;text-indent:0cm'><span style='font-size:10.0pt;font-family:Tahoma'>" + CurrentTestNum.ToString().PadLeft(3, '0') + "</span></p> </td>\n\n";
                    string answerMainfooter = "</tr>";
                    correctAnswersWriter.Write(answerMainHeader);
                    foreach (string answer in correctAnswers)
                    {
                        string answerHeader = "<td width=22 style='width:16.6pt;border:solid windowtext 1.0pt;border-left: none;padding:2.85pt 0cm 2.85pt 0cm;height:3.15pt'> <p class=MsoNormal align=center style='text-align:center;text-indent:0cm'><span lang=EN-US style='font-size:10.0pt;font-family:Tahoma'>";
                        string answerFooter = "</span></p></td>\n\n";
                        correctAnswersWriter.Write(answerHeader + answer + answerFooter);
                        correctAnswersWriter.Flush();
                    }
                    correctAnswersWriter.Write(answerMainfooter);
                    correctAnswersWriter.Flush();
                }
            }
        }

        private void WriteFooter(string fileName)
        {
            using (StreamWriter writer = new StreamWriter(fileName, true, Encoding.GetEncoding("windows-1251")))
            {
                string footerString = TestBuilder.Resource.Footer;
                writer.Write(footerString);
                writer.Flush();
            }
        }
    }
}
